<template>
  <div class="padding">
    <el-button type="primary" @click="customDialog?.open">追加设备</el-button>
    <el-table :data="deviceData">
      <el-table-column prop="id" label="编号"></el-table-column>
      <el-table-column
        prop="generation_type"
        label="设备类型"
      ></el-table-column>
      <el-table-column prop="power_output" label="功率">
        <template #default="scoped">
          {{ scoped.row.power_output + "KW" }}
        </template>
      </el-table-column>
      <el-table-column prop="voltage" label="电压">
        <template #default="scoped">
          {{ scoped.row.voltage + "V" }}
        </template>
      </el-table-column>
      <el-table-column prop="current" label="电流">
        <template #default="scoped">
          {{ scoped.row.current + "A" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scoped">
          <el-button type="primary" @click="openUpdate(scoped.row)"
            >修改</el-button
          >
          <el-button type="danger" @click="delect(scoped.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <CustomDialog ref="customDialog">
      <el-button type="danger" @click="customDialog?.close">取消</el-button>
      <el-button type="primary" @click="sure">确定</el-button>
    </CustomDialog>
    <CustomDialog ref="customUpdateDialog">
      <el-button type="danger" @click="customUpdateDialog?.close"
        >取消</el-button
      >
      <el-button type="primary" @click="update">确定</el-button>
    </CustomDialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import axios from "axios";
import CustomDialog, { Expose } from "./dialog.vue";
import { ElMessage } from "element-plus";

const deviceData = ref();
const customDialog = ref<Expose>();
const customUpdateDialog = ref<Expose>();

const getDevice = () => {
  axios.get("/api/getdevice").then((d) => {
    deviceData.value = d.data;
  });
};

getDevice();

const sure = () => {
  const formData = customDialog.value?.getFormData();
  axios.post("/api/addDevice", formData).then((d) => {
    ElMessage.success({
      message: d.data.message,
    });
    getDevice();
    customDialog.value?.close();
  });
};

const update = () => {
  const val = customUpdateDialog.value?.getFormData();
  axios.post("/api/updateDevice", val).then((d) => {
    ElMessage.success({
      message: d.data.message,
    });
    customUpdateDialog.value?.close();
    getDevice();
  });
};

const openUpdate = (row: any) => {
  customUpdateDialog.value?.updateFormData(row);
  customUpdateDialog.value?.open();
};

const delect = (id: number) => {
  axios.post("/api/delDevice", { id }).then((d) => {
    ElMessage.success({
      message: d.data.message,
    });
    getDevice();
  });
};
</script>

<style scoped></style>
